package org.geektimes.projects.microprofile.servlet;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.projects.microprofile.config.DefaultConfig;
import org.geektimes.projects.microprofile.config.source.ServletContextConfigSource;

import javax.annotation.Priority;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;

/**
 * 外部化配置加载器
 * @author biwin
 */
@Priority(1)
public class ServletContextConfigSourceInitializer implements ApplicationContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        servletContext.log("Priority : 1 (ConfigSource)");
        ServletContextConfigSource servletContextConfigSource = new ServletContextConfigSource(servletContext);
        ConfigProviderResolver providerResolver = ConfigProviderResolver.instance();
        ConfigBuilder configBuilder = providerResolver.getBuilder();
        ClassLoader classLoader = servletContext.getClassLoader();
        configBuilder.forClassLoader(classLoader);
        configBuilder.addDefaultSources();
        configBuilder.addDiscoveredSources();
        configBuilder.addDiscoveredConverters();
        configBuilder.withSources(servletContextConfigSource);
        Config config = configBuilder.build();
        providerResolver.registerConfig(config, classLoader);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
